package ddb.dbcore;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbManager {
    private int maxBatch;

    public DbManager() {
        maxBatch = 100;
    }

    public void setMaxBatch(int max) {
        maxBatch = max;
    }

    public DbTable executeSelect(String query) throws SQLException {
        DbTable table = new DbTable();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = DbConnection.getDBConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(query);
            table.initTable(rs);
        } catch (SQLException ex) {
            throw ex;
        } finally {
            rs.close();
            stmt.close();
            DbConnection.closeConnection(conn);
        }
        return table;
    }

    public int[] executeExecuteBatch(String[] queries) throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        int[] result = null;
        try {
            conn = DbConnection.getDBConnection();
            stmt = conn.createStatement();
            conn.setAutoCommit(false);
            for (int i = 0; i < queries.length; i++) {
                stmt.addBatch(queries[i]);
                if ((i + 1) % maxBatch == 0) {
                    result = stmt.executeBatch();
                }
            }
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException ex) {
            throw ex;
        } finally {
            stmt.close();
            DbConnection.closeConnection(conn);
        }
        return result;
    }

}
